package cc.customer.clue.service.Impl;

import cc.customer.clue.dao.ClueMapper;
import cc.customer.clue.dao.ClueTokenMapper;
import cc.customer.clue.domain.Clue;
import cc.customer.clue.domain.ClueToken;
import cc.customer.clue.service.ClueUtiService;
import cc.customer.common.service.impl.BaseService;
import cc.customer.cusDynamic.dao.CusDynamicMapper;
import cc.customer.cusDynamic.domain.CusDynamic;
import cc.customer.system.dao.SaleTagMapper;
import cc.customer.system.domain.SaleTag;
import cc.customer.utils.HttpClientUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

@Service
public class ClueUtilImpl extends BaseService<Clue>  implements ClueUtiService {

    private static final Logger log = LoggerFactory.getLogger(ClueUtilImpl.class);

    private static String defaultContentEncoding;
    @Autowired
    private ClueTokenMapper clueTokenMapper;
    @Autowired
    private CusDynamicMapper cusDynamicMapper;
    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private SaleTagMapper saleTagMapper;

    //形成签名
    @Override
    public void parseAutograph(CusDynamic dynamic){
        try {
            //客户id
            String accid = dynamic.getDyCusUuid();
            Example examples = new Example(Clue.class);
            examples.createCriteria().andEqualTo("cCusid",accid);
            List<Clue> clues = clueMapper.selectByExample(examples);
            if(clues.size()>0){
                Clue clue = clues.get(0);
                if("1".equals(clue.getcType())){
                    //广点通
                    sendGuangDianRollBack(clue,dynamic);
                }else if("2".equals(clue.getcType())){
                    //今日头条
                    sendTouTiaoRollBack(clue,dynamic);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("广点通发送回调信息失败:"+e.getMessage());
        }
    }


    private static String parsMethod(String label){
        String method = "";
        switch (label){
            case "已报名":
                method =  "LEADS_INEFFECT_REASION_DATA_DUPLICATION";
                break;
            case "咨询全日制":
                method =  "LEADS_INEFFECT_REASION_NO_INTENTION";
                break;
            case "咨询毕业学位":
                method =  "LEADS_INEFFECT_REASION_NO_INTENTION";
                break;
            case "非相关业务":
                method =  "LEADS_INEFFECT_REASION_NO_INTENTION";
                break;
            case "无效-不存在":
                method =  "LEADS_INEFFECT_REASION_EMPTY";
                break;
            case "联系不上":
                method =  "LEADS_INEFFECT_REASION_TEL_NOT_CONNECTED";
                break;
            case "拒绝沟通":
                method =  "LEADS_INEFFECT_REASION_TEL_NOT_CONNECTED";
                break;
            case "不符合要求":
                method =  "LEADS_INEFFECT_REASION_NO_INTENTION";
                break;
            case "重复名片":
                method =  "LEADS_INEFFECT_REASION_DATA_DUPLICATION";
                break;
            case "非本人":
                method =  "LEADS_INEFFECT_REASION_IDENTITY_MISMATCHED";
                break;
            case "其他":
                method =  "LEADS_INEFFECT_REASION_UNKOWN";
                break;
            default:
        }
        return method;
    }

    //发送广点通回调
    private void sendRollBack(String signature, String json){
        try {
            Map<String,String> head = new HashMap<>();
            head.put("X-Signature",signature);
            head.put("Accept","application/json");
            head.put("Content-Type","application/json");
            HttpClientUtil.sendPost("https://leads.qq.com/api/mv1/leads/report",json,head);
        }catch (Exception e){
            e.printStackTrace();
            log.error("广点通发送回调信息失败");
        }
    }

    /**广点通回调*/
    private void sendGuangDianRollBack(Clue clue, CusDynamic dynamic){
        try {
            Base64.Encoder encoder = Base64.getEncoder();
            Example example = new Example(ClueToken.class);
            example.createCriteria().andEqualTo("tAccid",clue.getcAccid());
            //线索token
            List<ClueToken> cltokenlist = clueTokenMapper.selectByExample(example);
            if(cltokenlist!=null){
                ClueToken clueToken =cltokenlist.get(0);
                String token = clueToken.gettTokenid();
                String secrect = clueToken.gettSecrect();

                Long timestamp = System.currentTimeMillis()/1000;
                String sha1 = DigestUtils.sha1Hex(token + "." + timestamp + "." +
                        secrect);
                String signature = encoder.encodeToString((token + "," + timestamp + ","
                        + sha1).getBytes());

                //转化意向
                String labelid = dynamic.getDyLabelAfter();
                String[] labelids = labelid.split(",");
                List<String> idlist = new ArrayList<>();
                for(String id:labelids){
                    idlist.add(id);
                }

                List<SaleTag> saleTagList = new ArrayList<>();
                Example example3 = new Example(SaleTag.class);
                example3.createCriteria().andIn("tagUuids",idlist);
                saleTagList = saleTagMapper.selectByExample(example3);
                List<String> taglist = new ArrayList<>();
                for(SaleTag saleTag:saleTagList){
                    taglist.add(saleTag.getTagName());
                }
                String method = "";
                if(taglist.size()>0){
                    for(String tagename:taglist){
                        method = parsMethod(tagename);
                        if(!StringUtils.isEmpty(method)){
                            break;
                        }
                    }
                }

                JSONObject json = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                JSONObject js = new JSONObject();
                js.put("leads_id",clue.getcLeadsid());
                js.put("leads_convert_type","LEADS_CONVERT_STATUS_DEPRECATED");
                js.put("leads_ineffect_reason",method);
                jsonArray.add(js);
                json.put("list",jsonArray);

                sendRollBack(signature,json.toJSONString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /***今日头条回调*/
    private void sendTouTiaoRollBack(Clue clue, CusDynamic dynamic){
        String access_token = "xxx";
        final String[] advertiser_ids = new String[]{clue.getcAccid()};
        final int source = Integer.parseInt(clue.getcSource());
        final String clue_id = clue.getcLeadsid();
        final int clue_convert_state = 1;

        // 请求地址
        String open_api_url_prefix = "https://ad.oceanengine.com/open_api/2/";
        String uri = "tools/clue/callback/";

        // 请求参数
        Map<String,Object> data = new HashMap(){
            {
                put("advertiser_ids", advertiser_ids);
                put("source", source);
                put("clue_id", clue_id);
                put("clue_convert_state", clue_convert_state);
            }
        };

        // 构造请求
        HttpPost httpEntity = new HttpPost(open_api_url_prefix + uri);

        httpEntity.setHeader("Access-Token",access_token);

        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;

        try {
            client = HttpClientBuilder.create().build();
            httpEntity.setEntity(new StringEntity(JSONObject.toJSONString(data), ContentType.APPLICATION_JSON));

            response = client.execute(httpEntity);
            if (response != null & response.getStatusLine().getStatusCode() == 200) {
                BufferedReader bufferedReader  = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer result = new StringBuffer();
                String line = "";
                while((line = bufferedReader.readLine()) != null) {
                    result.append(line);
                }
                bufferedReader.close();
                log.error("今日头条回调信息"+result.toString());
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
